﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Procure.Data.Context;

namespace Procure.Web.productType
{
    public partial class EditProductType : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ImageButton save = UmbracoPanel1.Menu.NewImageButton();
            save.ImageUrl = umbraco.GlobalSettings.Path + "/images/editor/save.gif";
            save.AlternateText = "Save";

            save.Click += new ImageClickEventHandler(save_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id = int.Parse(Request["id"]);
                ProcureDataContext context = DataFactory.GetDataContext();

                ProductType type = context.ProductTypes.FirstOrDefault(pt => pt.Id == id);

                if (type != null)
                {
                    ProductTypeName.Text = type.Name;
                    AttributesList.DataSource = context.Attributes;
                    AttributesList.DataBind();
                    foreach (ListItem item in AttributesList.Items)
                    {
                        var attr = type.ProductTypeAttributes.FirstOrDefault(pta => pta.AttributeId.ToString() == item.Value);
                        if (attr != null)
                            item.Selected = true;
                    }
                }
            }
        }

        void save_Click(object sender, ImageClickEventArgs e)
        {
            int id = int.Parse(Request["id"]);
            ProcureDataContext context = DataFactory.GetDataContext();

            ProductType type = context.ProductTypes.FirstOrDefault(pt => pt.Id == id);
            type.Name = ProductTypeName.Text;

            context.SubmitChanges();
        }
    }
}